<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>数据看板</title>
</head>
<body>
<div class="dashboard">
    <!-- 运输时效分析 -->
    <div class="chart-panel">
        <div class="chart-title">供应商运量统计
            <div class="chart-query-container">
                <label class="layui-form-label">请选择年月</label>
                <div class="layui-input-inline">
                    <input type="text" class="layui-input" id="ID-laydate-type-month1" placeholder="yyyy-MM">
                </div>
                <button class="chart-query-btn" id="chart1-query">查询</button>
            </div>
        </div>
        <div id="chart1" class="chart-container"></div>
    </div>

    <!-- 客户订单统计 -->
    <div class="chart-panel">
        <div class="chart-title">客户订单统计
            <div class="chart-query-container">
                <label class="layui-form-label">请选择年月</label>
                <div class="layui-input-inline">
                    <input type="text" class="layui-input" id="ID-laydate-type-month2" placeholder="yyyy-MM">
                </div>
                <button class="chart-query-btn" id="chart2-query">查询</button>
            </div>
        </div>
        <div id="chart2" class="chart-container"></div>
    </div>

    <!-- 计划与实际运量 -->
    <div class="chart-panel">
        <div class="chart-title">计划与实际运量
            <div class="chart-query-container">
                <label class="layui-form-label">请选择年</label>
                <div class="layui-input-inline">
                    <input type="text" class="layui-input" id="ID-laydate-type-year3" placeholder="yyyy">
                </div>
                <button class="chart-query-btn" id="chart3-query">查询</button>
            </div></div>
        <div id="chart3" class="chart-container"></div>
    </div>

    <!-- 异常事件分布 -->
    <div class="chart-panel">
<!--        <div class="chart-title">异常事件分布</div>-->
        <div id="chart4" class="chart-container"></div>
    </div>
</div>

<script>
    // 初始化所有图表
    function initCharts() {
        initChart1();
        initChart2();
        initChart3();
        // initChart4();
    }

    // 运输时效分析（散点图）
    function initChart1() {
        chart1 = echarts.init(document.getElementById('chart1'));
        loadChartData1(); // 默认加载数据
    }

    // 成本分布统计（柱状图）
    function initChart2() {
        chart2 = echarts.init(document.getElementById('chart2'));
        loadChartData2(); // 默认加载数据
    }

    // 运力利用率（折线图）
    function initChart3() {
        chart3 = echarts.init(document.getElementById('chart3'));
        loadChartData3(); // 初始化时加载数据
    }


    // 窗口大小变化时重置图表
    window.addEventListener('resize', () => {
        echarts.getInstanceByDom(document.getElementById('chart1'))?.resize();
        echarts.getInstanceByDom(document.getElementById('chart2'))?.resize();
        echarts.getInstanceByDom(document.getElementById('chart3'))?.resize();
        echarts.getInstanceByDom(document.getElementById('chart4'))?.resize();
    });

    // 添加事件监听
    document.getElementById('chart1-query').addEventListener("click", loadChartData1);
    document.getElementById('chart2-query').addEventListener("click",loadChartData2);
    document.getElementById('chart3-query').addEventListener('click',loadChartData3);
    // 加载图表数据
    async function loadChartData1() {
        const yearMonth = document.getElementById('ID-laydate-type-month1').value;
        const params = {
            partYearMonth: yearMonth ? parseInt(yearMonth.replace('-', '')) : null
        };

        try {
            const response = await fetch('http://localhost:8080/transportChild/SupplierStatistics', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            });

            const result = await response.json();
            if (result.status === 0 && result.data) {
                updateChart1(result.data);
            } else {
                console.error('供应商数据加载失败:', result.message);
            }
        } catch (error) {
            console.error('请求失败:', error);
        }
    }
    async function loadChartData2() {
        const yearMonth = document.getElementById('ID-laydate-type-month2').value;
        const params = {
            partYearMonth: yearMonth ? parseInt(yearMonth.replace('-', '')) : null
        };

        // try {
            const response = await fetch('http://localhost:8080/transportChild/CustomerStatistics', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(params)
            });

            const result = await response.json();
            if (result.status === 0 && result.data) {
                updateChart2(result.data);
            } else {
                console.error('数据加载失败:', result.message);
            }
        // } catch (error) {
        //     console.error('请求失败:', error);
        // }
    }
    // 加载图表3数据
    async function loadChartData3() {
        // const year = document.getElementById('ID-laydate-type-year3').value || '2025';
        const year = document.getElementById('ID-laydate-type-year3').value;

        try {
            const response = await fetch('http://localhost:8080/transportChild/VehicleStatistics', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ partYear: parseInt(year) })
            });

            const result = await response.json();
            if (result.status === 0 && result.data) {
                updateChart3(result.data);
            } else {
                console.error('数据加载失败:', result.message);
            }
        } catch (error) {
            console.error('请求失败:', error);
        }
    }
    function updateChart1(data) {
        const xData = [];
        const seriesData = [];

        data.forEach(item => {
            xData.push(item.supplierName);
            seriesData.push(item.count);
        });

        const option = {
            xAxis: {
                type: 'category',
                data: xData,
                axisLabel: {
                    rotate: 0,
                    interval: 0,
                    formatter: function(value) {
                        const maxLength = 2;
                        return value.length > maxLength ?
                            value.substr(0, maxLength) + '…' :
                            value.padEnd(maxLength, ' ');
                    }
                },
                name: '供应商'
            },
            yAxis: {
                type: 'value',
                name: '运量（台）'
            },
            series: [{
                data: seriesData,
                type: 'bar',
                barWidth: '30px',
                itemStyle: {
                    color: '#1890ff'
                }
            }],
            tooltip: {
                trigger: 'axis',
                formatter: '{b}: {c}台'
            },
            dataZoom: [{
                type: 'slider',
                show: true,
                xAxisIndex: [0],
                start: 0,
                end: 100,
                bottom: 10
            }]
        };

        chart1.setOption(option);
    }
    // 更新图表
    function updateChart2(data) {
        // 处理数据格式
        const xData = [];
        const seriesData = [];

        data.forEach(item => {
            xData.push(item.consignorName); // 假设返回数据包含consignorName字段
            seriesData.push(item.count);    // 假设返回数据包含count字段
        });

        const option = {
            xAxis: {
                type: 'category',
                data: xData,
                axisLabel: {
                    rotate: 0,
                    interval: 0, // 显示所有标签
                    formatter: function(value) {
                        const maxLength = 4;
                        return value.length > maxLength ?
                            value.substr(0, maxLength) + '…' :
                            value.padEnd(maxLength, ' ');
                    }
                },
                name: '委托商'
            },
            yAxis: {
                type: 'value',
                name: '运量（台）'
            },
            series: [{
                data: seriesData,
                type: 'bar',
                barWidth: '30px',  // 固定柱宽
                itemStyle: {
                    color: '#1890ff'
                }
            }],
            tooltip: {
                trigger: 'axis',
                formatter: '{b}: {c}台'
            },
            dataZoom: [{
                type: 'slider',
                show: true,
                xAxisIndex: [0],
                start: 0,
                end: 100,
                bottom: 10  // 滚动条位置
            }]
        };

        chart2.setOption(option);
    }
    // 更新图表3
    function updateChart3(data) {
        // 处理数据格式
        const xData = [];
        const planData = [];
        const actualData = [];

        data.forEach(item => {
            // 转换月份格式 202501 -> 1月
            const monthNum = parseInt(item.month.substring(4));
            xData.push(`${monthNum}月`);
            planData.push(item.planCount);
            actualData.push(item.actualCount);
        });

        const option = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['计划运量', '实际运量']
            },
            xAxis: {
                type: 'category',
                data: xData,
                name: '月份',
                axisLabel: {
                    interval: 0 // 强制显示所有标签
                }
            },
            yAxis: {
                type: 'value',
                name: '运量（台）'
            },
            series: [
                {
                    name: '计划运量',
                    type: 'line',
                    data: planData,
                    smooth: true,
                    itemStyle: {
                        color: '#5470c6' // 蓝色
                    }
                },
                {
                    name: '实际运量',
                    type: 'line',
                    data: actualData,
                    smooth: true,
                    itemStyle: {
                        color: '#91cc75' // 绿色
                    }
                }
            ]
        };

        chart3.setOption(option);
    }
    layui.use(['laydate'], function() {
        const laydate = layui.laydate;
        // chart1 年月选择器
        laydate.render({
            elem: '#ID-laydate-type-month1',
            type: 'month',
            format: 'yyyy-MM',
            value: '2025-04'
        });
    // 年月选择器
        laydate.render({
            elem: '#ID-laydate-type-month2',
            type: 'month',
            format: 'yyyy-MM',
            value: '2025-04' // 设置默认年月
        });

        // 年选择器
        laydate.render({
            elem: '#ID-laydate-type-year3',
            type: 'year',
            value: '2025' // 设置默认年
        });
    });

    // 页面加载初始化
    initCharts()
</script>
</body>
</html>